﻿using Microsoft.AspNetCore.StaticFiles;
using System.Web;
using Yz.Base;
using Yz.Base.ParaModels;
using Yz.Core.Extensions;
using Yz.Core.Tools;
namespace Yz.FileService.Middlewares
{
    public class DownloadMiddleware : BaseUploadMiddleware, IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            #region 跨域上传
            if (context.Request.Method.Equals(HttpMethods.Options, StringComparison.OrdinalIgnoreCase))
            {
                base.AddHttpOptionHeader(context);
            }
            #endregion

            #region 后台post上传
            else if (context.Request.Method.Equals(HttpMethods.Post, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    #region 验证token
                    var validRes = await ValidateTokenAsync(context);
                    if (!validRes.Item1.IsEmpty())
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = validRes.Item1
                        }.ToJsonStr());
                        return;
                    }
                    string appId = validRes.Item2;
                    #endregion

                    var sv = context.Request.Form["application/json"].FirstOrDefault();
                    if (sv.IsEmpty())
                    {
                        sv = context.Request.Form["data"].FirstOrDefault();
                    }
                    string fileId = "";
                    if (!sv.IsEmpty())
                    {
                        var paraFileId = sv.ToJsonObject<ParaFileId>();
                        if (paraFileId == null || string.IsNullOrEmpty(paraFileId.Id))
                        {
                            await context.Response.WriteAsync(new VmUpFileBase()
                            {
                                Msg = "参数不正确！"
                            }.ToJsonStr());
                            return;
                        }
                        fileId = paraFileId.Id;
                    }
                    string filePath = fileId.ToDes3Decrypt();
                    if (!filePath.Contains(appId))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "您没有权限下载此文件！"
                        }.ToJsonStr());
                        return;
                    }
                    if (!File.Exists(_uploadConfig.PhysicalPath + filePath))
                    {
                        await context.Response.WriteAsync(new VmUpFile()
                        {
                            Msg = "您要下载的文件不存在！"
                        }.ToJsonStr());
                        return;
                    }
                    if (!string.IsNullOrEmpty(_uploadConfig.VirtualPath))
                    {
                        filePath = filePath.Replace(_uploadConfig.VirtualPath, _uploadConfig.PhysicalPath);
                    }
                    using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        string fileName = filePath.Substring(filePath.LastIndexOf("/") + 1);
                        string fileExt = fileName.Substring(fileName.LastIndexOf("."));
                        var provider = new FileExtensionContentTypeProvider();
                        var contentType = provider.Mappings[fileExt];
                        fileName = HttpUtility.UrlEncode(fileName);
                        context.Response.Clear();
                        context.Response.Headers.Add("fileName", fileName);
                        context.Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
                        context.Response.ContentType = contentType;
                        var bytes = new byte[stream.Length];
                        await context.Response.Body.WriteAsync(bytes);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    YzNLog.Error(ex);
                    await context.Response.WriteAsync(new VmUpFileBase()
                    {
                        Msg = "文件下载失败"
                    }.ToJsonStr());
                }
            }
            #endregion

            #region 非法上传
            else
            {
                await base.AddHttpNotAllowedAsync(context);
            }
            #endregion 
        }
    }
}
